import * as util from '@/common/utils/common'
import {  updateDrawInfo, getDrawInfo } from '@/api/draw/DrawInfoApi'
import { getToken } from '@/common/utils/auth'
import { Message } from 'element-ui'
import draw from '@/components/draw/index'


export default {
  components: {
    draw
  },
  name: 'drawEditor',
created () {
  this.getParams()
},
mounted() {
  this.init();
},
  watch : {
    '$route': 'getParams'
  },
  data() {
    return {
      // 实例化后的导图对象
      draw: {},
      drawData: {
          'data': { 'text': '根结点', 'id': 2 },
          'children': []
      },
      id:'',
      name:'',
      uploadUrl: process.env.BASE_API + '/resource/upload/file',
      fileUrl: '',

    }
  },
  computed: {
    headers(){
      let accessToken = getToken();
      return {
        'x-access-token': accessToken
      }
    }
  },
  methods: {
    init(){
      let self =  this;
      self.getParams();
    },
    getParams () {
       this.id = this.$route.query.id
      //  this.name = this.$route.query.name
        // 如果是params 传参，那就是this.$route.params.site
    },
    saveDraw(){
      let self =  this;
       this.draw.exportData('json').then(function(content){
          let drawInfo = {"id":self.id, "content":content};
          updateDrawInfo(drawInfo).then((response) => {
              if (util.isRequestSuccess(response)) {
                self.$notify({ title: '成功', message: '保存成功', type: 'success', duration: 2000 })
              } else {
                self.$notify({ title: '失败', message: '保存失败!', type: 'error', duration: 2000 });
              }
            })
      });

    },

     // 返回列表
    toDrawList(){
      this.$router.go(-1)
    },

    // 图片上传 begin
    beforeUpload(file) {
      const isJPG = file.type.indexOf('image/')==0;
      const isLt5M = file.size / 1024 / 1024 < 5;

      if (!isJPG) {
        this.$message.error('请上传图片格式的文件!');
      }
      if (!isLt5M) {
        this.$message.error('上传图片大小不能超过 5MB!');
      }
      return isJPG && isLt5M;
    },
    handleUploadSuccess(res, file) {
      if(util.isUploadSuccess(res)){
        this.fileUrl = res.data;
        this.draw.execCommand('image', res.data,  'aaa');
      }else{
        Message({
          message: res.message,
          type: 'error',
          duration: 5 * 1000
        });
      }
    },
    // 图片上传 end

    // 导出图片start
    exportDataImgPng(){
        const exportType = 'png';
        let self = this;
        this.draw.exportData(exportType).then(function(content){
            const filename = self.name + '.png';
            self.downloadFileByBlob(content, filename);
        });
    },
    downloadFileByBlob(content, filename) {
      // 导出方案1
      const blob = this.b64toBlob(content)
      var dlLink = document.createElement('a');
      dlLink.download = filename;
      dlLink.href = URL.createObjectURL(blob);
      document.body.appendChild(dlLink);
      dlLink.click();
      document.body.removeChild(dlLink);

      // 导出方案2
      // var dlLink = document.createElement('a');
      // dlLink.download = filename;
      // dlLink.href = content
      // document.body.appendChild(dlLink);
      // dlLink.click();
      // document.body.removeChild(dlLink);
    },
    b64toBlob(dataURI) {
      var byteString = atob(dataURI.split(',')[1]);
      var ab = new ArrayBuffer(byteString.length);
      var ia = new Uint8Array(ab);

      for (var i = 0; i < byteString.length; i++) {
          ia[i] = byteString.charCodeAt(i);
      }
      return new Blob([ab], { type: 'image/png' });
    },
    // 导出图片end

    exportData(){
        console.log(this.exportDataByType('json'));
    },
    exportDataByType(exportType){
      return this.draw.exportData(exportType).then(function(content){
        switch(exportType){
          case 'json':
            return $.parseJSON(content)
            break;
          case 'png':
              return content
          default:
            console.log(content);
            return content;
        }
      });
    },
    importData(){
      const data = '{"root":{"data":{"text":"Design project","id":2},"children":[{"data":{"text":"Designsy","id":113},"children":[]},{"data":{"text":"Designsy","id":124},"children":[]}]},"template":"default","theme":"fresh-blue","version":"1.4.43"}'

      this.draw.importJson($.parseJSON(data));
    },
    getData(){
      console.log(this.draw.exportData('json',{}))
      console.log(this.draw.exportJson())
    },
     drawHandle (draw) {
       this.draw = draw;
    },


    insertImg () {
       // 插入图片示例
      this.draw.execCommand('image', 'http://localhost:6001/static/img/head.3f65dd5.jpg',  'aaa');
    },
    clearImg () {
      this.draw.execCommand('image', '');
    },
    insertLink () {
        this.$prompt('请输入链接地址', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /(http|https):\/\/([\w.]+\/?)\S*/,
          inputErrorMessage: '链接地址格式不正确'
        }).then(({ value }) => {
          this.draw.execCommand('HyperLink', value, 'aaa');
        }).catch(() => {
          this.$message({
          type: 'info',
          message: '取消输入'
          });
        });
    },
    clearLink () {
       this.draw.execCommand('HyperLink', '');
    },
    insertResource () {
        this.$prompt('请输入注释', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(({ value }) => {
          this.draw.execCommand('resource',value);
        }).catch(() => {
          this.$message({
          type: 'info',
          message: '取消输入'
          });
        });
    },
    clearResource () {
      this.draw.execCommand('resource',null);
    },

    setPriority (val) {

      if(!val){
        this.draw.execCommand('Priority', null);
      }else{
        this.draw.execCommand('Priority', parseInt(val));
      }

    },
    setProgress (val) {
       this.draw.execCommand('Progress', parseInt(val));
    },
    insertNote () {
       this.draw.execCommand('note', 'werwerwer**aa**');
    },
    clearNote () {
       this.draw.execCommand('note', null);
    },

    insertText () {
       this.draw.execCommand('text', '测试插入文本...');
    },
    ArrangeUp () {
       this.draw.execCommand('ArrangeUp');
    },
    ArrangeDown () {
       this.draw.execCommand('ArrangeDown');
    },
    setBackground (command) {
       this.draw.execCommand('background',command);
    },
    ExpandToLevel () {
       this.draw.execCommand('ExpandToLevel', 9999);
    },
    resetlayout () {
       this.draw.execCommand('resetlayout');
    },
    zoom() {
       this.draw.execCommand('zoom', 100);
    },
    zoomIn() {
       this.draw.execCommand('zoomIn', 100);
    },
    hand () {
       this.draw.execCommand('hand');
    },
    camera() {
       this.draw.execCommand('camera', this.draw.getRoot(), 600);
    },

    expand () {
       this.draw.execCommand('expand', true);
    },
    RemoveNode () {
       this.draw.execCommand('RemoveNode');
    },
    setLayout (val) {
      this.draw.execCommand('template', val);
    },
    setTheme (val) {
      this.draw.execCommand('theme', val);
    },

  },
  created() {
    // window.addEventListener('hashchange', this.afterQRScan)
  },
  destroyed() {
    // window.removeEventListener('hashchange', this.afterQRScan)
  }
}

/**
draw.execCommand('HyperLink', result.url, result.title || '');
draw.execCommand('HyperLink', null)
draw.queryCommandState("bold") || draw.execCommand("bold");
draw.execCommand("Priority", p);
draw.execCommand("Progress", parseInt(p) + 1);
draw.execCommand("image", resp.data.url);
draw.execCommand('Image', '')
draw.execCommand('note', content);
draw.execCommand('note', null)
draw.execCommand("text", "中心主题");
draw.execCommand('ArrangeUp')
draw.execCommand('ArrangeDown');
draw.execCommand('background', bgColor)
draw.execCommand('ExpandToLevel', 9999)
draw.execCommand('fontfamily', f.val)


draw.execCommand('resetlayout')
draw.execCommand('zoom', 100);
draw.execCommand('zoomIn')
draw.execCommand('hand')
draw.execCommand('camera', draw.getRoot(), 600);

draw.execCommand('RemoveNode');
draw.execCommand('resource', resource);
draw.execCommand('expand', true);
*/
